package com.dingdang.filter;

import com.alibaba.fastjson.JSONObject;
import com.dingdang.data.Result;
import com.dingdang.em.ResultEnum;
import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class RequestFilter extends ZuulFilter {
    //每秒产生1000个令牌  一般每秒产生的令牌是自己请求并发的多少,一般1000~2000左右   这里给3是方便测试
    private static final RateLimiter RATE_LIMITER = RateLimiter.create(3);

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        System.out.println("获取令牌");
        boolean tryAcquire = RATE_LIMITER.tryAcquire();
        // 如果获取不到就直接停止
        if(!tryAcquire){
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
            //获取response
            HttpServletResponse response = requestContext.getResponse();
            try {
                response.setContentType("text/html;charset=utf-8");
                Result result = Result.response(ResultEnum.TOO_MANY_REQUESTS);
                response.getWriter().write(JSONObject.toJSONString(result));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return null;
    }
}
